package com.test.hanlp.participle.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import com.hankcs.hanlp.seg.common.Term;
import com.test.hanlp.participle.po.CustomDictionaryPo;
import com.test.hanlp.participle.po.CustomTermPo;
import com.test.hanlp.participle.repository.ICustomDictionaryRepository;
import com.test.hanlp.participle.repository.ICustomTermRepository;
import com.test.hanlp.participle.service.IWordSegmentationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @Package: com.test.hanlp.participle.service.impl
 * @ClassName WordSegmentationService
 * @Description: 词根服务
 * @Author: ky.zhang
 * @Date 2024/7/16 18:42
 * @Version v1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WordSegmentationService implements IWordSegmentationService {

    private final ICustomTermRepository customTermRepository;

    private final ICustomDictionaryRepository customDictionaryRepository;

    @PostConstruct
    public void init() {
        final List<CustomDictionaryPo> allDicts = customDictionaryRepository.findAllByDeletedFalse();
        allDicts.forEach(customDictionaryPo -> CustomDictionary.add(customDictionaryPo.getWord()));
        CustomDictionary.reload();
    }

    /**
     * @param text <br>
     * @Method: segment <br>
     * @Param:
     * @Return: java.util.Map<java.lang.String, java.lang.String> <br>
     * @Description：<br>分词
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:48 <br>
     * @Version： V1.0<br>
     */
    @Override
    public synchronized Map<String, String> segment(final String text) {
        // 执行分词
        final List<Term> termList = HanLP.segment(text);
        final Map<String, String> resultMap = new HashMap<>(200);
        // 将分词结果转换为Map结构
        Map<String, String> wordMap = new HashMap<>();
        for (Term term : termList) {
            final String word = term.word;
            String replacement = HanLP.convertToPinyinString(word, "_", true);
            Optional<CustomTermPo> customTerm = customTermRepository.findByWordAndDeletedFalse(word);
            if (customTerm.isPresent()) {
                final String tmp = customTerm.get().getReplacement();
                if (StrUtil.isNotBlank(tmp)) {
                    replacement = tmp;
                }
            }
            resultMap.put(word, replacement);
        }
        // 输出分词结果和词性
        System.out.println(wordMap);
        return resultMap;
    }

    /**
     * @param word <br>
     * @Method: addHanlpCustomDictionary <br>
     * @Param:
     * @Return: boolean <br>
     * @Description：添加自定义词典<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:49 <br>
     * @Version： V1.0<br>
     */
    @Override
    public synchronized boolean addHanlpCustomDictionary(final String word) {
        CustomDictionary.add(word);
        CustomDictionary.reload();
        customDictionaryRepository.save(new CustomDictionaryPo().setWord(word).setDeleted(false));
        return true;
    }

    /**
     * @param word <br>
     * @Method: removeHanlpCustomDictionary <br>
     * @Param:
     * @Return: boolean <br>
     * @Description：移除自定义词典<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:49 <br>
     * @Version： V1.0<br>
     */
    @Override
    public synchronized boolean removeHanlpCustomDictionary(final String word) {
        CustomDictionary.remove(word);
        CustomDictionary.reload();
        customDictionaryRepository.save(new CustomDictionaryPo().setWord(word).setDeleted(true));
        return true;
    }

    /**
     * @Method: queryCustomDictionary <br>
     * @Param: <br>
     * @Return: java.lang.String <br>
     * @Description：查询所有自定义词典<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:49 <br>
     * @Version： V1.0<br>
     */
    @Override
    public String queryCustomDictionary() {
        final List<CustomDictionaryPo> allDicts = customDictionaryRepository.findAllByDeletedFalse();
        return allDicts.toString();
    }

    /**
     * @Method: queryTerms <br>
     * @Param: <br>
     * @Return: java.lang.String <br>
     * @Description：查询所有自定义术语<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:49 <br>
     * @Version： V1.0<br>
     */
    @Override
    public String queryTerms() {
        List<CustomTermPo> terms = customTermRepository.findAllByDeletedFalse();
        return terms.toString();
    }

    /**
     * @param word
     * @param replacement <br>
     * @Method: addTerm <br>
     * @Param:
     * @Return: boolean <br>
     * @Description：添加自定义术语<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:50 <br>
     * @Version： V1.0<br>
     */
    @Override
    public boolean addTerm(String word, String replacement, String abbreviation) {
        // 添加自定义词汇
        customTermRepository.save(new CustomTermPo().setWord(word).setReplacement(replacement).setAbbreviation(abbreviation));
        return true;
    }

    /**
     * @param word <br>
     * @Method: removeTerm <br>
     * @Param:
     * @Return: boolean <br>
     * @Description：删除自定义术语<br>
     * @Author： ky.zhang<br>
     * @Date： 2024/7/17 15:50 <br>
     * @Version： V1.0<br>
     */
    @Override
    public boolean removeTerm(String word) {
        Optional<CustomTermPo> customTermOpt = customTermRepository.findByWordAndDeletedFalse(word);
        customTermOpt.ifPresent(customTerm -> {
            customTerm.setDeleted(true);
            customTermRepository.save(customTerm);
        });
        return true;
    }

    /**
     * 分词
     */
    @Override
    public List<CustomTermPo> segment1(String text) {
        // 执行分词
        final List<Term> termList = HanLP.segment(text);
        final List<CustomTermPo> customTermPoList = new ArrayList<>();

        for (Term term : termList) {
            final String word = term.word;
            Optional<CustomTermPo> customTerm = customTermRepository.findByWordAndDeletedFalse(word);
            if (customTerm.isPresent()) {
                log.info("分词成功，自定义术语对象：{}", customTerm);
                CustomTermPo customTermPo = new CustomTermPo();
                customTermPo.setWord(customTerm.get().getWord());
                customTermPo.setReplacement(customTerm.get().getReplacement());
                customTermPo.setAbbreviation(customTerm.get().getAbbreviation());
                customTermPo.setComment(text);
                customTermPoList.add(customTermPo);
            } else {
                customTermPoList.add(new CustomTermPo().setWord(word).setReplacement(null).setAbbreviation(null));
            }
        }
        return customTermPoList;
    }
}
